<template>
  <div class="lit-decrypt-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h3>Lit解密工具</h3>
    </div>

    <!-- 文本解密区域 -->
    <div class="section">
      <div class="section-header">
        <h3 class="section-title">文本解密工具</h3>
        <div class="header-actions">
          <el-button
            @click="clearTextData"
            :disabled="!textInputData && !textDecryptResult"
            size="default"
          >
            <SvgIcon name="reload" size="16px" />
            清空数据
          </el-button>
        </div>
      </div>

      <!-- 输入和结果并排显示 -->
      <div class="decrypt-layout">
        <!-- 输入区域 -->
        <div class="decrypt-section input-section">
          <div class="subsection-header">
            <h4 class="subsection-title">加密数据输入</h4>
            <div class="format-tips">
              <el-tag size="small" type="info">
                支持纯文本格式的加密字符串
              </el-tag>
            </div>
          </div>

          <div class="input-area">
            <div class="input-wrapper">
              <el-input
                v-model="textInput"
                type="textarea"
                placeholder="请输入需要解密的加密字符串"
                class="data-input"
                resize="none"
                :autosize="false"
                :style="{ height: '150px' }"
              />
            </div>

            <div class="input-actions">
              <el-button
                @click="decryptTextData"
                type="success"
                :disabled="!textInputData || isTextDecrypting"
                :loading="isTextDecrypting"
              >
                <SvgIcon name="cloud-lock-open" size="16px" />
                {{ isTextDecrypting ? '解密中...' : '开始解密' }}
              </el-button>
              <el-button @click="pasteFromClipboard">
                <SvgIcon name="copy" size="16px" />
                从剪贴板粘贴
              </el-button>
            </div>
          </div>
        </div>

        <!-- 结果区域 -->
        <div class="decrypt-section result-section">
          <div class="subsection-header">
            <h4 class="subsection-title">解密结果</h4>
            <div class="result-actions" v-if="textDecryptResult">
              <el-button @click="copyTextResult" size="small">
                <SvgIcon name="copy" size="14px" />
                复制结果
              </el-button>
              <el-button @click="downloadTextResult" size="small">
                <SvgIcon name="save" size="14px" />
                下载结果
              </el-button>
            </div>
          </div>

          <!-- 解密结果显示 -->
          <div class="result-container">
            <div>
              <pre v-if="textDecryptResult" class="result-content">{{
                formatTextDecryptResult(textDecryptResult)
              }}</pre>
              <div v-else-if="textDecryptError" class="result-content error">
                {{ textDecryptError }}
              </div>
              <div v-else class="result-content placeholder">暂无数据</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 日志文件解密区域 -->
    <div class="section">
      <div class="section-header">
        <h3 class="section-title">日志文件解密工具</h3>
        <div class="header-actions">
          <el-button
            @click="clearLogData"
            :disabled="!selectedFile"
            size="default"
          >
            <SvgIcon name="reload" size="16px" />
            清空数据
          </el-button>
        </div>
      </div>

      <!-- 文件上传区域 -->
      <div class="upload-section">
        <div class="upload-area">
          <!-- 平台选择 -->
          <div class="platform-type-selector">
            <label class="platform-type-label">平台类型:</label>
            <el-radio-group v-model="platform" class="platform-type-options">
              <el-radio label="ios">
                <SvgIcon name="iOS" size="16px" />
                iOS
              </el-radio>
              <el-radio label="android">
                <SvgIcon name="brand-android" size="16px" />
                Android
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 文件上传 -->
          <div class="file-upload-section">
            <div class="upload-wrapper">
              <div
                class="upload-dropzone"
                :class="{ 'drag-over': isDragOver, 'has-file': selectedFile }"
                @dragover.prevent="isDragOver = true"
                @dragleave.prevent="isDragOver = false"
                @drop.prevent="handleFileDrop"
                @click="$refs.fileInput.click()"
              >
                <input
                  ref="fileInput"
                  type="file"
                  @change="handleFileSelect"
                  accept=".xlog"
                  style="display: none"
                />

                <div v-if="!selectedFile" class="upload-placeholder">
                  <div class="upload-icon">
                    <SvgIcon name="file" size="48px" />
                  </div>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽文件到此处</p>
                    <p class="upload-desc">支持 .xlog格式文件</p>
                  </div>
                </div>

                <div v-else class="file-info">
                  <div class="file-icon">
                    <SvgIcon name="file" size="32px" />
                  </div>
                  <div class="file-details">
                    <div class="file-name">{{ selectedFile.name }}</div>
                    <div class="file-size">
                      {{ formatFileSize(selectedFile.size) }}
                    </div>
                  </div>
                  <el-button
                    @click.stop="removeFile"
                    size="small"
                    type="danger"
                    :icon="'delete'"
                  >
                    <SvgIcon name="delete" size="16px" />
                  </el-button>
                </div>
              </div>
            </div>

            <div class="upload-actions">
              <el-button
                @click="decryptAndDownloadFile"
                type="success"
                :disabled="!selectedFile || isLogDecrypting"
                :loading="isLogDecrypting"
              >
                <SvgIcon name="save" size="16px" />
                {{ isLogDecrypting ? '解密中...' : '解密并下载' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件信息弹窗 -->
    <el-dialog v-model="showFileInfo" title="文件信息" width="500px">
      <div v-if="fileInfo" class="file-info-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="文件名">
            {{ fileInfo.file_name }}
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(fileInfo.file_size) }}
          </el-descriptions-item>
          <el-descriptions-item label="平台">
            {{ fileInfo.platform }}
          </el-descriptions-item>
          <el-descriptions-item label="解密时间">
            {{ fileInfo.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="原始文件">
            <el-tag
              :type="fileInfo.original_file?.exists ? 'success' : 'danger'"
              size="small"
            >
              {{ fileInfo.original_file?.exists ? '✓ 存在' : '✗ 不存在' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="解密文件">
            <el-tag
              :type="fileInfo.decrypted_file?.exists ? 'success' : 'danger'"
              size="small"
            >
              {{ fileInfo.decrypted_file?.exists ? '✓ 存在' : '✗ 不存在' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SvgIcon from '@/views/components/SvgIcon.vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

export default {
  name: 'LitDecrypt',
  components: {
    SvgIcon,
  },
  data() {
    return {
      // 文本解密相关
      textInput: '',
      isTextDecrypting: false,
      textDecryptResult: null,
      textDecryptError: null,
      textDecryptTime: null,

      // 日志解密相关
      platform: 'ios',
      selectedFile: null,
      isDragOver: false,
      isLogDecrypting: false,
      auditId: null,
      showFileInfo: false,
      fileInfo: null,
    }
  },
  computed: {
    textInputData() {
      return this.textInput.trim()
    },
  },
  methods: {
    // 文本解密方法
    clearTextData() {
      this.textInput = ''
      this.textDecryptResult = null
      this.textDecryptError = null
      this.textDecryptTime = null
    },

    async pasteFromClipboard() {
      try {
        const text = await navigator.clipboard.readText()
        this.textInput = text
        ElMessage.success('粘贴成功')
      } catch (err) {
        console.error('粘贴失败:', err)
        ElMessage.error('粘贴失败')
      }
    },

    async decryptTextData() {
      if (!this.textInputData) {
        return
      }

      this.isTextDecrypting = true
      this.textDecryptError = null
      this.textDecryptResult = null

      try {
        const requestData = { data: this.textInput }
        const response = await request.post('/lit/crypto/decrypt', requestData)

        this.textDecryptResult = response.data
        this.textDecryptTime = new Date().toLocaleString()
        ElMessage.success('解密成功')
      } catch (error) {
        this.textDecryptError = error.message || '解密失败，请检查输入数据'
        ElMessage.error(this.textDecryptError)
      } finally {
        this.isTextDecrypting = false
      }
    },

    formatTextDecryptResult(result) {
      return this.formatContent(result)
    },

    formatContent(content) {
      if (!content) return ''

      // 尝试解析为JSON并格式化
      if (typeof content === 'string') {
        try {
          const parsed = JSON.parse(content)
          return JSON.stringify(parsed, null, 2)
        } catch (e) {
          // 不是JSON格式，直接返回原始内容
          return content
        }
      }

      // 如果已经是对象，格式化为JSON
      if (typeof content === 'object') {
        return JSON.stringify(content, null, 2)
      }

      return String(content)
    },

    async copyTextResult() {
      try {
        const result = this.formatTextDecryptResult(this.textDecryptResult)
        await navigator.clipboard.writeText(result)
        ElMessage.success('复制成功')
      } catch (err) {
        console.error('复制失败:', err)
        ElMessage.error('复制失败')
      }
    },

    downloadTextResult() {
      const result = this.formatTextDecryptResult(this.textDecryptResult)

      // 判断是否为JSON格式
      let isJson = false
      let mimeType = 'text/plain'
      let fileExtension = 'txt'

      // 检查原始解密结果是否为JSON
      if (
        typeof this.textDecryptResult === 'object' &&
        this.textDecryptResult !== null
      ) {
        isJson = true
      } else if (typeof this.textDecryptResult === 'string') {
        // 检查字符串是否为有效的JSON
        try {
          const parsed = JSON.parse(this.textDecryptResult)
          if (typeof parsed === 'object' && parsed !== null) {
            isJson = true
          }
        } catch (e) {
          // 不是有效的JSON字符串
        }
      }

      // 如果不是JSON，再检查格式化后的结果是否看起来像JSON
      if (
        !isJson &&
        result.trim().startsWith('{') &&
        result.trim().endsWith('}')
      ) {
        try {
          JSON.parse(result)
          isJson = true
        } catch (e) {
          // 不是有效的JSON
        }
      }

      if (isJson) {
        mimeType = 'application/json'
        fileExtension = 'json'
      }

      const blob = new Blob([result], { type: mimeType })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `text_decrypt_result_${new Date().getTime()}.${fileExtension}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      ElMessage.success('下载成功')
    },

    // 日志解密方法
    clearLogData() {
      this.selectedFile = null
      this.auditId = null
    },

    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        // 检查文件格式
        const fileName = file.name.toLowerCase()
        if (!fileName.endsWith('.xlog')) {
          ElMessage.error('只支持 .xlog 格式的文件')
          event.target.value = '' // 清空文件选择
          return
        }
        this.selectedFile = file
        this.auditId = null
      }
    },

    handleFileDrop(event) {
      event.preventDefault()
      this.isDragOver = false

      const files = event.dataTransfer.files
      if (files.length > 0) {
        const file = files[0]
        // 检查文件格式
        const fileName = file.name.toLowerCase()
        if (!fileName.endsWith('.xlog')) {
          ElMessage.error('只支持 .xlog 格式的文件')
          return
        }
        this.selectedFile = file
        this.auditId = null
      }
    },

    removeFile() {
      this.selectedFile = null
      this.auditId = null
    },

    async decryptAndDownloadFile() {
      if (!this.selectedFile) {
        ElMessage.error('请先选择要解密的文件')
        return
      }

      // 验证文件
      if (this.selectedFile.size === 0) {
        ElMessage.error('文件大小为0，请选择有效的文件')
        return
      }

      this.isLogDecrypting = true

      // 显示上传提示
      ElMessage.info({
        message: `正在上传并解密 ${this.selectedFile.name}，请稍候...`,
        duration: 0, // 持续显示直到手动关闭
        showClose: false,
      })

      try {
        const formData = new FormData()
        formData.append('log', this.selectedFile)

        // 添加调试信息
        console.log('上传文件信息:', {
          fileName: this.selectedFile.name,
          fileSize: this.selectedFile.size,
          fileType: this.selectedFile.type,
          platform: this.platform,
        })

        // 验证FormData
        console.log('FormData entries:', Array.from(formData.entries()))

        const url = `/lit/log/decode?platform=${this.platform}`
        const response = await request.post(url, formData, {
          headers: {
            'Content-Type': undefined, // 让axios自动设置正确的Content-Type
          },
        })

        if (response.success) {
          // 尝试从不同位置获取audit_id
          let auditId = null
          if (response.data.file_info && response.data.file_info.audit_id) {
            auditId = response.data.file_info.audit_id
          } else if (response.data.audit_id) {
            auditId = response.data.audit_id
          } else if (response.audit_id) {
            auditId = response.audit_id
          } else {
            // 如果响应中没有audit_id，尝试获取最新的审计记录
            auditId = await this.fetchLatestAuditRecord()
          }

          if (auditId) {
            this.auditId = auditId
            await this.downloadDecryptedFile()
            // 关闭之前的上传提示
            ElMessage.closeAll()
            ElMessage.success('文件解密成功，已开始下载！')
          } else {
            // 关闭之前的上传提示
            ElMessage.closeAll()
            ElMessage.warning('解密成功，但无法获取下载信息')
          }

          // 清空文件选择
          this.selectedFile = null
          this.auditId = null
        } else {
          // 关闭之前的上传提示
          ElMessage.closeAll()
          console.error('解密失败响应:', response)
          ElMessage.error(response.message || '解密失败')
        }
      } catch (error) {
        console.error('解密请求失败:', error)

        // 更详细的错误信息
        let errorMessage = '解密失败，请检查文件格式和平台选择'
        if (error.error_code === '1002') {
          errorMessage = '文件上传失败，请检查文件是否有效并重新选择'
        } else if (error.response?.status === 413) {
          errorMessage = '文件过大，请选择较小的文件'
        } else if (error.response?.status === 400) {
          errorMessage = '请求参数错误，请检查文件格式'
        } else if (error.message) {
          errorMessage = error.message
        }

        // 关闭之前的上传提示
        ElMessage.closeAll()
        ElMessage.error(errorMessage)
      } finally {
        this.isLogDecrypting = false
      }
    },

    async fetchLatestAuditRecord() {
      try {
        // 获取最新的日志解密审计记录
        const response = await request.get(
          '/lit/audit/records?operation_type=log_decrypt&page=1&per_page=1',
        )
        if (
          response.success &&
          response.data.records &&
          response.data.records.length > 0
        ) {
          const latestRecord = response.data.records[0]
          // 检查是否是刚刚创建的记录（时间差在1分钟内）
          const recordTime = new Date(latestRecord.created_at)
          const now = new Date()
          const timeDiff = (now - recordTime) / 1000 // 秒

          if (timeDiff < 60 && latestRecord.success) {
            // 1分钟内且成功的记录
            return latestRecord.id
          }
        }
      } catch (error) {
        console.warn('获取最新审计记录失败:', error)
      }
      return null
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    async downloadOriginalFile() {
      if (!this.auditId) return

      try {
        const response = await fetch(
          `/api/lit/file/download/${this.auditId}?file_type=original`,
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('access_token')}`,
            },
          },
        )

        if (response.ok) {
          const blob = await response.blob()
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `original_${this.selectedFile?.name || 'file'}`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
          ElMessage.success('原始文件下载成功')
        } else {
          ElMessage.error('文件下载失败')
        }
      } catch (error) {
        console.error('下载原文件失败:', error)
        ElMessage.error('文件下载失败')
      }
    },

    async downloadDecryptedFile() {
      if (!this.auditId) return

      try {
        const response = await fetch(
          `/api/lit/file/download/${this.auditId}?file_type=decrypted`,
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('access_token')}`,
            },
          },
        )

        if (response.ok) {
          const blob = await response.blob()
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `decrypted_${this.selectedFile?.name || 'file'}`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
          ElMessage.success('解密文件下载成功')
        } else {
          ElMessage.error('文件下载失败')
        }
      } catch (error) {
        console.error('下载解密文件失败:', error)
        ElMessage.error('文件下载失败')
      }
    },

    async viewFileInfo() {
      if (!this.auditId) return

      try {
        const response = await request.get(`/lit/file/info/${this.auditId}`)
        if (response.success) {
          this.fileInfo = response.data
          this.showFileInfo = true
        } else {
          ElMessage.error('获取文件信息失败')
        }
      } catch (error) {
        console.error('获取文件信息失败:', error)
        ElMessage.error('获取文件信息失败')
      }
    },

    closeFileInfo() {
      this.showFileInfo = false
      this.fileInfo = null
    },
  },
}
</script>

<style scoped>
.lit-decrypt-container {
  padding: 20px;
  /* background: white; */
  min-height: calc(100vh - 74px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color);
}

.page-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.section {
  margin-bottom: 8px;
  /* background-color: white; */
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
  padding: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color);
}

.section-title {
  font-size: 16px;
  color: #555;
  margin: 0;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.decrypt-layout {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.decrypt-section {
  /* background: white; */
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 10px;
  flex: 1;
  min-width: 0;
}

.subsection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color);
}

.subsection-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.format-tips {
  display: flex;
  align-items: center;
}

.result-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.input-area {
  margin-top: 10px;
}

.input-wrapper {
  margin-bottom: 10px;
}

.input-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.data-input {
  width: 100%;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

.data-input :deep(.el-textarea__inner) {
  height: 150px !important;
  min-height: 150px !important;
  max-height: 150px !important;
  resize: none !important;
}

.input-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 8px;
}

/* 解密结果显示样式 */
.result-container {
  margin-top: 16px;
}

.result-content {
  width: 100%;
  height: 200px;
  padding: 6px;
  margin: 0;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.4;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
  /* background: #ffffff; */
  text-align: left;
  color: #333;
}

.result-content.error {
  background: #fff2f0;
  border-color: #ffccc7;
  color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: inherit;
}

.result-content.placeholder {
  /* background: #ffffff !important; */
  border-color: #ddd;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: inherit;
  font-size: 16px;
  cursor: default;
}

/* 日志解密样式 */
.upload-section {
  margin-top: 10px;
}

.upload-area {
  margin-top: 10px;
}

/* 平台类型选择器 */
.platform-type-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
  padding: 8px 0;
}

.platform-type-label {
  display: block;
  margin-bottom: 0;
  font-weight: 500;
  color: #333;
  font-size: 14px;
  min-width: 80px;
}

.platform-type-options {
  display: flex;
  align-items: center;
  gap: 20px;
}

.file-upload-section {
  margin-top: 10px;
}

.upload-wrapper {
  margin-bottom: 10px;
}

.upload-dropzone {
  border: 2px dashed var(--el-border-color);
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  /* background: #fafafa; */
}

.upload-dropzone:hover {
  border-color: #67c23a;
  /* background: #f0f9f5; */
}

.upload-dropzone.drag-over {
  border-color: #67c23a;
  /* background: #f0f9f5; */
}

.upload-dropzone.has-file {
  padding: 20px;
  /* background: #f9f9f9; */
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.upload-icon {
  opacity: 0.6;
}

.upload-text {
  text-align: center;
}

.upload-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
}

.upload-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  /* background: white; */
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
}

.file-icon {
  flex-shrink: 0;
}

.file-details {
  flex: 1;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.upload-actions {
  display: flex;
  justify-content: center;
}

.file-info-details {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .decrypt-layout {
    flex-direction: column;
    gap: 20px;
  }

  .result-content {
    height: 150px;
  }
}

@media (max-width: 768px) {
  .lit-decrypt-container {
    padding: 16px;
  }

  .section {
    padding: 16px;
  }

  .decrypt-layout {
    gap: 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .input-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .result-content {
    height: 120px;
    font-size: 11px;
  }

  .upload-dropzone {
    padding: 30px 15px;
  }
}
</style> 